<template>
  <div class="pager" v-show="hideIfNoData && totalPage">
    <span
      :class="{ disable: currentPage <= 1 }"
      class="page"
      @click="change(currentPage - 1)"
      >❮</span
    >
    <span
      v-for="(page, index) in pages"
      :key="page.toString() + index"
      :class="{ other: typeof page === 'string', active: page === currentPage }"
      class="page"
      @click="change(page)"
      >{{ page }}</span
    >
    <span
      :class="{ disable: currentPage >= totalPage }"
      class="page"
      @click="change(currentPage + 1)"
      >❯</span
    >
  </div>
</template>

<script>
export default {
  name: 'Pager',
  props: {
    totalPage: {
      required: true,
      type: Number
    },
    currentPage: {
      required: true,
      type: Number
    },
    hideIfNoData: {
      type: Boolean,
      default: true
    }
  },
  computed: {
    pages() {
      let pages = [
        1,
        this.totalPage,
        this.currentPage,
        this.currentPage + 1,
        this.currentPage + 2,
        this.currentPage - 1,
        this.currentPage - 2
      ]
        .filter(n => n > 0 && n <= this.totalPage)
        .sort((a, b) => a - b)

      return this.unique(pages).reduce((acc, current, index, array) => {
        acc.push(current)
        const next = array[index + 1]
        if (next) {
          next - current > 1 ? acc.push('...') : null
        }
        return acc
      }, [])
    }
  },

  methods: {
    // 去重
    unique(arr) {
      const obj = {}
      arr.forEach(n => {
        obj[n] = true
      })
      return Object.keys(obj).map(n => {
        return parseInt(n, 10)
      })
    },

    change(n) {
      if (n < 1 || n > this.totalPage) return
      this.$emit('update:currentPage', n)
      this.$emit('change', n)
    }
  }
}
</script>

<style scoped>
.pager {
  display: inline-flex;
  align-items: center;
}
.pager .page {
  display: inline-block;
  line-height: 13px;
  padding: 2px 5px;
  margin: 0 5px;
  font-size: 13px;
  border: 1px solid #e2e2e2;
  border-radius: 3px;
  color: #778087;
  cursor: pointer;
}
.page:nth-child(1) {
  margin-left: 0;
}
.page:hover {
  background-color: #f0f0f0;
  color: #000;
}
.page.other {
  border: none;
  margin: 0 !important;
  padding: 0 !important;
}
.page.active {
  padding: 3px 6px;
  border: 1px solid #bbb;
  background-color: #f0f0f0;
}
.page.disable:hover {
  background-color: transparent;
  color: #778087;
}
</style>
